
// handle user info
// login...
// update user info

// namespace define !!! not class 
em.accmgr = {};
em.accmgr = function () {

	// em.accmgr.objName = 'AccMgr';	
	//var self = em.accmgr; // <- window 
	//em.accmgr.users = CDB.userdata;
	var users = CDB.userdata;
	
	function getUsers() {
		return users;
	};
	

	
	
	/*
		 define public 
	*/
	return { 
		objName: 'AccMgr: ',
		
		// cbs 
		resultLogin : function( type, o) {
			var self = this;
			debug.log(self, type, o);
			var types = type.split(".");
			switch( types[0]) {
				case 'ERROR':
				debug.log(self, 'ERROR');
				if ( types[1] == 'startGM' ) {
						em.accmgr.login();
					// }
				} 
				// go next ... for sp30 
				else if ( types[1] == 'LOGIN_INFO') {
					em.cbs.userchanged.fire(-1);
				} 
				
				break;
				case'DATA':
					if( types[1] == 'userinfo') {
						// update user info 
					/*
							"user":{"id":18949,"nick":"greateload","nationid":1,"level":42,"money":345,"guild":"greate","guildid":262,
					"gpower":1,"gflag":97,"protection":0,"p_end":1322486844,"status":0,
					"city":[
						{"id":22289,"name":"centercast","landtype":3,"x":61,"y":19},
						{"id":22336,"name":"heaven","landtype":4,"x":61,"y":18},
						{"id":22349,"name":"Spacecastl","landtype":2,"x":60,"y":17},
						{"id":22423,"name":"Forward","landtype":5,"x":62,"y":17}],
					"conq":[0,0,null,5],
					"gift":[{"id":168,"msg":"","s":0}],"pvp":0
					},
					*/
					$.extend(em.accmgr, o );	// lv, .... 
					debug.log(em.accmgr, em.accmgr);
					debug.log(self, self);
					
					// update db with userinfo 
					var u_info = CDB.getCurUserInfo();
					u_info.guild = o.guild;
					u_info.userid = o.id;
					u_info.nick = o.nick;
					
					// notify UI 
					em.infoview.connected(true);
					
					/// update user info  to view 
					// var castles = CDB.getUserCtsl(username);
					
					
					// set cstl to cstl mgr
					em.cstlmgr.setUserCstls(o.city);
					
					// update db !!! must do 
					CDB.updateCstls(o.city);
					
					// notify user info 
					em.infoview.updateUserinfo('login', o); 	// data.ret.user 
					
				}
				else if ( types[1] == 'questinfo' ) {
					// update user server
					var userinfo = CDB.getCurUserInfo();
					debug.log (self, 3,  ' resultLogin:: questinfo  ::: ' + o);
					userinfo.questinfo= o;		// update key
				}				
				else if ( types[1] == 'key') {
					// update user key 
					var userinfo = CDB.getCurUserInfo();
					var newkey  = o;
					debug.log (self, 3,  ' resultLogin:: prev Key :: Store !!!!!!! ' + userinfo.key);
					userinfo.key = newkey;		// update key
					debug.log (self, 3,  ' resultLogin:: new  Key :: Store !!!!!!! ' + newkey);
					
					// set local storage
					CUtil.saveStorage('sessionkey_' +  CDB.getCurUserName() , newkey );
					// localStorage.setItem('sessionkey_' +  CDB.getCurUserName() , newkey );
					 
			 		// reflect to Query class
					CQuery.setQueryKey(newkey);


				}
				else if ( types[1] == 'server' ) {
					// update user server
					var userinfo = CDB.getCurUserInfo();
					var server  = o;
					debug.log (self, 3,  ' resultLogin:: server  ::: ' + server);
					userinfo.serverinfo.serverurl = server;		// update key
					
			 		// reflect to Query class
					CQuery.setServerurl(server);
					
					// em.infoview.show(logininfo) ;	
					
				}

			// $.extend( userinfo.castles , data.ret.user.city);
			// debug.log(self, 'process Data', o);
			break;
			case 'NOTY':
			debug.log(self, 'NOTYT', o);
			break;
		}
	},
	
		getUsersName: function() {
			var names= [] , i =0;
			var users= getUsers();
			for ( ; i < users.length; i++) {
				names.push ( users[i].name);
				}
			return names;
		},
		
			/*
			{"quest":[
		{"id":48,"grade":0,"status":0,"done":1},
		{"id":49,"grade":0,"status":1,"done":1},
	*/
		getQusetState: function( id ) {
					var userinfo = CDB.getCurUserInfo();
					debug.log (self, 3,  ' resultLogin:: questinfo  ::: '  , userinfo.questinfo);
					// find  by id
					var quest ;
					$.each ( userinfo.questinfo, function (i, el){
						 if (  el.id == id ) {
						 	quest = el ;
						 	return false; // exit each
						 }
					});
					
					return quest;
		},
		
		//  when select user:   
		// before process sequenc !!!  
		// first set user specific datas.  
		// called by controller 
		setCurUser : function(username){
			var self = this;
				// DB set,
			// set db table for this user  
			CDB.setCurUser(username);
			
			// update view 
 			em.infoview.setUserInfo( CDB.getCurUserInfo());
	 		// set query acc to user device : 
			// caution !! after setCurUser !!! 
			// update sesseion key from stroage 
						

			var keyname = 'sessionkey_' +  CDB.getCurUserName(); 
			
			if ( username =='leniencsy%40gmail.com' || username =='james_PVP' 
					|| username == 'greate_PVP' 
					|| username == 'mp001') {
				var userinfo = CDB.getCurUserInfo();
				CUtil.saveStorage(keyname, userinfo.key );
			}

// temp to erase key 						
 // if ( username == 'greate_PVP' ) {
				// var userinfo = CDB.getCurUserInfo();
				// CUtil.saveStorage(keyname, userinfo.key );
// 
 // }
						
			// var sessionkey = localStorage.getItem(keyname );
			var sessionkey = CUtil.getStorage(keyname);
			
			var userinfo = CDB.getCurUserInfo();
			if ( sessionkey ) {
				userinfo.key =  sessionkey;		// update key with storage key
				debug.log (self, 3,  ' setCurUser:: Get Stored Key ::  ' + sessionkey); 			
			} else {
				// if no key in storage  : save this key 
				CUtil.saveStorage(keyname, userinfo.key );
				debug.log (self, 3,  ' setCurUser:: Save Key first !! ::  ' + userinfo.key);
			}
						
			// CQuery.setQueryOptions(username, userinfo.device, userinfo.droid);
			CQuery.setQueryOptions(userinfo);

				// server url 
			var server = userinfo.serverinfo.serverurl;		
			debug.log (self, 3,  ' setCurUser:: server  ::: ' + server);
					
			CQuery.setServerurl(server);
 
 
		},
		
		
	/*
		Start GM ======
	*/	
		
			// func after move cstl   for start 
		afterMove_login: function() {
				var self = this;
				// get studys & update user info			
				debug.log(self, 'this', this, 'cb_cstlmove in start GM  '); 
				setTimeout( function() { self.getStudys(); } ,CUtil.RandTime(500));			
		},
		
		// for set users  ADV AR , DEF Form  
		getStudys: function() {
			var self = this;
			debug.log(self,  'this', this,'after1CstlMove :: ..get getStudys  '	);
			
			//remove cb 
			em.cbs.cstlmove1done.remove( self.cb_cstlmove );
			
			// var self = this;
			var jcb = $.Callbacks();
			
			jcb.add( function (data) {
				var studys = data.ret;
				 // {"code":0,"ret":[[1,1,1],[2,1,1],[3,0,1]],"ext":[4,4]};
				debug.log(self, 'this', this, 'got studys :', studys);
				// update solders & go next step : get heroes 
				em.cstlmgr.updateStudies(studys);
				
				// update acc info 
				var AdvAr = CDB.GetStudyLv(studys, CDB.STUDYS.ADV_ARMOR );
				CDB.setUserAdvAr(AdvAr);
				debug.log(this, 'set Adv Ar ', AdvAr);

				var DefForm = CDB.GetStudyLv(studys, CDB.STUDYS.DEF_FORMATION );
				CDB.setUserDefForm(DefForm);
				debug.log(this, 'set Def Form: ', DefForm);
				
				// fire user changed... move here for both sp30, normal  
				em.cbs.userchanged.fire();		
				 
			});
			em.tasks.getStudys(jcb);
			

		},		
		
		// entry function for change user
		// after setCurUser by controller  
		startGM:  function( username) {
			var self = this;
			debug.log(self, 'this', this, 'Strat GM ' , username);
			
			// noty UI 
			em.infoview.connected(false);
			
			// not to will be removed cb 
			if ( ! this.resultcb ) {
				em.cbs.userlogin.add( this.resultcb = function(type, o) { self.resultLogin(type, o);} );
			}
			
			// em.tasks4user.startGM(CDB.getCurUserName());
			em.tasks4user.startGM(username);
			
			// cb when cstl move done 
			em.cbs.cstlmove1done.add( self.cb_cstlmove = function( ){
				debug.log(self, 'this', this, 'cb_cstlmove in start GM  '); 
				// self.afterMove();}  );
				self.afterMove_login();}  );
		},
		
/*

		// when fail : try login 
		// result :  when fail   send global event ( login result ) 
		startSPGM:  function( username ) {
			var self = this;
			debug.log(self, 'this', this, 'Strat GM ');

			// register  cb for start gm  & login  result 			
			if ( ! this.resultcb ) {
				em.cbs.userlogin.add( this.resultcb = function(type, o) { self.resultLogin(type, o);} );
			}
			
			em.tasks4user.startGM( username );
			
		},
		*/


		
		login: function() {
			var self = this;
			// set cb
			// var defaultuser = 'james';
			var defaultuser = '';
			// james !!! check 
			if (CDB.getCurUserName() == defaultuser ) {
				//======================= set default user ... 
				debug.log (self, 3,  ' login:: Default User .. no change session key ::  ' ); 	
				em.accmgr.setCurUser(defaultuser);
				em.infoview.setUserInfo( CDB.getCurUserInfo());
				return;
			}
			
			if ( ! this.resultcb ) {
				em.cbs.userlogin.add( this.resultcb = function(type, o) { self.resultLogin(type, o);} );		// unique check !!!  
			}
			
			em.tasks4user.processLogin(CDB.getCurUserName());
		},
	
	
		//; 각 유저별 사용할 DA array  [ 6,5,4,3, ]
		getCurDAs: function()	{
			console.log('getCurDAs ==========');
			return CDB.getUserDAsArr(CDB.getCurUser());
			
		},
		
		// user grade update : lv 
		updateGrade: function (grade){
			var userinfo = CDB.getCurUserInfo();
			userinfo.grade = grade;
			// em.infoview.updateUserinfo(grade); 	// data.ret.user 
			em.infoview.updateUserinfo('grade', userinfo); 	// data.ret.user 
			
		},
		// for each user's hnt state
		hntstate: function() {
				this.count = 0;
				this.lasttime = 0;
				this.DAsfiltered = false;
				// this.addCnt = function() {	count++;};
				// this.getCnt = function() {	return count;};
				// this.getLasttime = function(){ return lasttime;};
				// this.setLasttime = function(last){  lasttime = last;};
				
			var self = this;
			return {
				bNeedtoRemake: function(){ 
								if( ! self.DAsfiltered || self.count > 5 || 
									CUtil.TimeDiffNowAbs( self.lasttime) > 60*60*1000 ) {
										return true;
									} else return false;},
				madeFavDAsArr: function() { self.DAsfiltered = true; self.count = 0; 
										self.lasttime = new Date().getTime();
										console.log( 'madeFavDAsArr   => ' , self.lasttime ) ; 
										},
				
				hntDoWoFavDAs: function() { self.count++;},
				setFlagRemakeDAsArr: function() { self.DAsfiltered=false;}
			}
			
		}(),

	};
}();

